﻿using System;
using System.Web;

namespace Sherwood.Imaging.Providers
{
    public class VirtualPathSegmentProvider : IStringProvider
    {
        private readonly INumberProvider _startAtSegmentIndex;
        private readonly INumberProvider _segmentsToRead;

        public VirtualPathSegmentProvider(int startAtSegmentIndex)
            : this(new StaticNumberProvider(startAtSegmentIndex))
        {
        }

        public VirtualPathSegmentProvider(int startAtSegmentIndex, int segmentsToRead)
            : this(new StaticNumberProvider(startAtSegmentIndex), new StaticNumberProvider(segmentsToRead))
        {
        }

        public VirtualPathSegmentProvider(INumberProvider startAtSegmentIndex)
            : this(startAtSegmentIndex, null)
        {
        }

        public VirtualPathSegmentProvider(INumberProvider startAtSegmentIndex, INumberProvider segmentsToRead)
        {
            _startAtSegmentIndex = startAtSegmentIndex;
            _segmentsToRead = segmentsToRead;
        }

        public IBooleanProvider RemoveFirstSegmentSeparator { get; set; }

        public string GetString()
        {
            var context = HttpContext.Current;
            var request = context.Request;
            var path = request.Url.AbsolutePath.Substring(request.FilePath.Length);
            int startIndex = path.IndexOf("/");
            var startAt = _startAtSegmentIndex.GetNumber();
            for (int i = 0; i < startAt; i++)
            {
                startIndex = path.IndexOf("/", startIndex + 1);
                if (startIndex == -1)
                    throw new ArgumentException("Invalid path");
            }
            if (_segmentsToRead != null)
            {
                var endIndex = startIndex;
                var segmentsCount = _segmentsToRead.GetNumber();
                for (int i = 0; i < segmentsCount; i++)
                {
                    endIndex = path.IndexOf("/", endIndex + 1);
                    if (endIndex == -1)
                        throw new ArgumentException("Invalid path");
                }
                if (RemoveFirstSegmentSeparator != null && RemoveFirstSegmentSeparator.GetValue())
                    startIndex++;
                return path.Substring(startIndex, endIndex - startIndex);
            }
            if (RemoveFirstSegmentSeparator != null && RemoveFirstSegmentSeparator.GetValue())
                startIndex++;
            return path.Substring(startIndex);
        }
    }
}